package ru.spbau.database.group3.parser;

import ru.spbau.database.group3.queryEvaluator.Instruction;
import ru.spbau.database.group3.queryEvaluator.ErrorInstruction;
import ru.spbau.database.group3.queryEvaluator.InsertInstruction;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: stas
 * Date: 1/29/13
 * Time: 12:58 PM
 */
public class InsertCmd extends abstractCmd {
    public InsertCmd() {
        super(StringConstants.INSERT);
    }

    @Override
    public Instruction process(String cmd) throws IOException {
        try {
            String tableName = getTableName(cmd);
            List<String> col_names = getColNames(cmd);
            List<String> values = getValues(cmd);
            return new InsertInstruction(tableName, col_names, values);
        } catch (Exception e) {
            return new ErrorInstruction(e.getMessage());
        }
    }

    private String getTableName(String cmd) {
        int begin = StringConstants.INSERT.length();
        int end = cmd.indexOf("(");
        return cmd.substring(begin, end).trim();
    }

    private ArrayList<String> getColNames(String cmd) {
        String str = cmd.substring(cmd.indexOf("("), cmd.indexOf(StringConstants.VALUES)).trim();
        String[] cols = str.substring(1, str.length() - 1).split(",");
        ArrayList<String> colNames = new ArrayList<String>();
        for(String s : cols) {
            colNames.add(s.trim());
        }
        return colNames;
    }

    private ArrayList<String> getValues(String cmd) {
        int begin = cmd.indexOf("(", cmd.indexOf(StringConstants.VALUES)) + 1;
        int end = cmd.lastIndexOf(")");
        String[] val = cmd.substring(begin, end).trim().split(",");
        ArrayList<String> values = new ArrayList<String>();
        for(String s : val) {
            values.add(s.trim());
        }
        return values;
    }
}
